---
--类名: CaptainTips.lua
--创建日期: 2018-9-22
--创建人: 宋建邦
--功能描述: 船长室tips
--修改内容:
local BaseIcon = Res.BaseIcon
local GRes = Res
local Res = {
    CaptainTipsCsb = "ui2/room/Node_room_tips.csb",
    CaptainTipsStr1Node = "ui2/room/room_tips_1.csb",
    CaptainTipsStr2Node = "ui2/room/room_tips_2.csb",
    CaptainTipsStr3Node = "ui2/room/room_tips_3.csb",
}

local CaptainTips = class("CaptainTips",function()
    return ccui.Layout:create()
end)

function CaptainTips:ctor()
    self._root = cc.CSLoader:createNode(Res.CaptainTipsCsb)
    self:setContentSize(self._root:getContentSize())
    ccui.Helper:doLayout( self._root )

    self.itemNode = cc.CSLoader:createNode(BaseIcon)
    self.itemNode:retain()

    self:addChild(self._root)

    self.btnObtain = self._root:findChild("Panel/btn_obtain")
    self.titleLbl = self._root:findChild("Panel/tlt")
    self:initButton()
    self:initListView()
end

function CaptainTips:initListView()
    local listView = ccui.ListView:create()
    -- listView:setBackGroundColor(display.COLOR_RED)
    -- listView:setBackGroundColorOpacity(70)
    -- listView:setBackGroundColorType(1)    

    local sv = self._root:findChild("Panel/ScrollView")
    listView:setContentSize(sv:getContentSize())
    listView:setAnchorPoint(sv:getAnchorPoint())
    listView:setPosition(cc.p(sv:getPositionX(), sv:getPositionY()))
    listView:setBounceEnabled(true)
    sv:getParent():addChild(listView)
    sv:hide()

    self.lstView = listView
end

function CaptainTips:initButton()
    self.btn = self._root:findChild("Panel/btn_obtain")
    self.btnLbl = self._root:findChild("Panel/btn_obtain/name")
    self.btn:addClickEventListener(function(sender)
        if self._data then
            self:cancel(true)
            if self._data.type == "obj" then
                if self.selectedObj then
                    if self.model:hasCollect(checknumber(self.selectedObj.ID)) then
                        local newID = checknumber(self.selectedObj.ID)
                        if newID == self.currentCollectID then
                            newID = 0
                        end
                        local lcfg = self.model:locationConfig(self.locationID)
                        if newID ~= 0 or (lcfg and checknumber(lcfg.remove) ~= 0) then
                            app:sendMsg("CaptainController", "reqSetLocation", self.locationID, newID)
                        end
                    else
                        app:sendMsg("CaptainController", "showObtainView", self.selectedObj.getResource, self.selectedObj.resourceFrom, self.selectedObj.name)
                    end
                end
            elseif self._data.type == "str" then
                local nothave = false
                if not self.model:hasCollect(self.currentBgID) and self.currentBgID ~= 0 then
                    self.currentBgID = self._data.curBg
                    nothave = true
                end

                if not self.model:hasCollect(self.currentFrameID) and self.currentFrameID ~= 0 then
                    self.currentFrameID = self._data.curFrame
                    nothave = true
                end

                if not self.model:hasCollect(self.currentColorID) then
                    self.currentColorID = self._data.curColor
                    nothave = true
                end

                if nothave then
                    display.pushToast(L("ErrHasntCollector"))
                end

                local cid = self.currentColorID
                local bid = self.currentBgID
                local fid = self.currentFrameID
                local function checkCB(str)
                    app:sendMsg("CaptainController", "reqSetString", str, cid, bid, fid)
                end
    
                local gettext = self.textField:getText()
                app:sendMsg("CaptainController", "checkString", gettext, checkCB)
            end
            app:sendMsg("CaptainController", "hideCaptainTips")
        end
    end)
end

function CaptainTips:refresh(data)
    if data == nil then
        return
    end

    self._data = data
    self.model = data.model

    local gap = 80
    local loc = cc.p(gap, (display.height - self._root:findChild("Panel"):getContentSize().height) * 0.5)
    if data.lid then
        local cfg = self.model:locationConfig(data.lid)
        if cfg and checknumber(cfg.tipsLocation) == 2 then
            loc = cc.p(display.width - self._root:findChild("Panel"):getContentSize().width - gap, loc.y)
        end
    end
    self._root:findChild("Panel"):setPosition(loc)

    if data.type == "obj" then
        self:refreshObjs(data)
    elseif data.type == "str" then
        self:refreshStr(data)
    end

    -- self._root:findChild("Panel"):setPositionY((display.height - self._root:findChild("Panel"):getContentSize().height) * 0.5)

    -- if data.align then
    --     local panel = self._root:findChild("Panel")
    --     if data.align.left then
    --         panel:setPositionX(math.max(0, data.align.left - panel:getContentSize().width))
    --     elseif data.align.right then
    --         if data.align.right + panel:getContentSize().width > display.width then
    --             panel:setPositionX(display.width - panel:getContentSize().width)
    --         else
    --             panel:setPositionX(data.align.right)
    --         end
    --     end
    -- end
end

function CaptainTips:refreshSelectCollect(data, preview)
    self.btnObtain:show()
    if self.model then
        self.btnLbl:setString(L"captain_tips_btn_select")
        if not self.model:hasCollect(checknumber(data.ID)) then
            -- self.btnObtain:show()
            self.btnLbl:setString(L"captain_tips_btn_obtain")
        end

        if self.currentCollectID == checknumber(data.ID) then
            self.btnLbl:setString(L"captain_tips_btn_unselect")
            local lcfg = self.model:locationConfig(self.locationID)
            if lcfg and checknumber(lcfg.remove) == 0 then
                self.btnLbl:setString(L"captain_tips_btn_selected")
            end        
        end

        if self._data.captainView and preview then
            self._data.captainView:setLocationObj(self.locationID, checknumber(data.ID))
        end
    end
end

function CaptainTips:cancel(cancel)
    if cancel then
        if self._data.captainView and self.locationID then
            self._data.captainView:setLocationObj(self.locationID, self.currentCollectID)
        end
    end
    if self._data.captainView then
        self._data.captainView:highLishtPosition(nil, true)
    end
    if self._data.captainView and self._data.type == "str" then
        if self._data.captainView.restoreString then
            self._data.captainView.restoreString()
        end
        self._data.captainView:setStringConfig(self._data.curStr, self._data.curColor, self._data.curBg, self._data.curFrame)
    end
end

function CaptainTips:getRow()
    local l = ccui.Layout:create()
    l:setLayoutType(ccui.LayoutType.HORIZONTAL)
    l:setContentSize(cc.size(336,76))
    l:setBackGroundColor(cc.c3b(78, 78, 78))

    local gap = ccui.Layout:create()
    gap:setContentSize(cc.size(12, 78))
    l:addChild(gap)

    l.items = {}
    for i = 1, 4 do
        local bi = self.itemNode:clone()-- cc.CSLoader:createNode(BaseIcon)        
        bi:setContentSize(bi:findChild("Panel"):getContentSize())
        l:addChild(bi)
        local gap = ccui.Layout:create()
        gap:setContentSize(cc.size(2, 78))
        l:addChild(gap)
        table.insert(l.items, bi)

        bi:findChild("Panel"):hide()
        bi:findChild("Panel/Panel_num"):hide()
        bi:findChild("Panel/level"):hide()
        bi:findChild("Panel/icon"):loadTexture("art/item_icon/itemicon_71112101.png")
        bi:findChild("Panel/selected"):hide()
        bi.select = function(preview)
            if self.lastSelect then
                self.lastSelect:hide()
            end
            self.lastSelect = bi:findChild("Panel/selected")
            self.lastSelect:show()
    
            self.selectedObj = bi.data
            self:refreshSelectCollect(bi.data, preview)
        end
        bi:findChild("Panel"):addClickEventListener(function(sender)
            bi.select(true)
        end)

        bi.setItem = function(data)
            bi.data = data
            bi:findChild("Panel"):show()
            local ygou = bi:findChild("Panel/room_e")
            local ggou = bi:findChild("Panel/room_curr")

            if self.model then
                local mask = bi:findChild("Panel/mask")
                if self.currentCollectID == checknumber(data.ID) then
                    ggou:show()
                elseif self.model:collectUsed(checknumber(data.ID)) then
                    ygou:show()
                end

                if self.model:hasCollect(checknumber(data.ID)) then
                    mask:hide()
                else
                    mask:show()
                end
            end
            
            -- bi:findChild("Panel/icon"):loadTexture("art/item_icon/itemicon_71112101.png")
            bi:findChild("Panel/icon"):loadTexture(data.iconPath.."/"..data.icon..".png")
            bi:findChild("Panel/grade"):loadTexture(GRes.Qulity_Icon_Bg[checknumber(data.quality)])
        end
    end

    return l
end

function CaptainTips:addTypeItems(items)
    local rows = {}
    local function getIcon(idx)
        local r = math.ceil(idx/4)
        if not rows[r] then
            rows[r] = self:getRow()
        end

        return rows[r].items[math.fmod(idx-1, 4) + 1]
    end

    for i, v in ipairs(items) do
        local icn = getIcon(i)
        icn.setItem(v)
        if i == 1 then
            icn.select()
        end
        -- self.model:hasCollect(checknumber(v.ID))
    end

    for i, v in ipairs(rows) do
        self.lstView:pushBackCustomItem(v)
    end
end

function CaptainTips:refreshObjs(data)
    self.locationID = data.lid
    self.currentCollectID = data.curID
    self.titleLbl:setString(L(data.lcfg.locationName))
    self.lstView:removeAllChildren()

    self.btnObtain:hide()
    -- self.btnLbl:setString("选用")

    if data.items and #data.items > 0 then
        self:addTypeItems(data.items)
    end
end

function CaptainTips:resetNodeSize(n)
    n:setContentSize(n:findChild("Panel"):getContentSize())
end

function CaptainTips:getStrCom()
    local n1 = cc.CSLoader:createNode(Res.CaptainTipsStr1Node)
    self:resetNodeSize(n1)

    self.textField = n1:findChild("Panel/TextField")
    self.textField = display.replaceTextFieldWithEditBox(self.textField)

    self.textField:registerScriptEditBoxHandler(function(strEventName,sender)
        if strEventName == "changed" then
            local cs = self.textField:getText()
            local ul = string.utf8len(cs)
            local bl = cs:len()
            local al = (ul*3 - bl)/2
            local sl = (ul - al) * 2 + al

            if sl > checknumber(GD:getSystemPar("captainRoomWordNum", 30))then
                self.textField:setText(self.lastcaptainstring or cs)
                display.pushToast(L("captain_string_too_long"))
            else
                self.lastcaptainstring = cs
                self:preViewString()
            end
        end
    end)
    return n1
end

function CaptainTips:preViewString()
    if self._data.captainView then
        self._data.captainView:setStringConfig(self.textField:getText(), self.currentColorID, self.currentBgID, self.currentFrameID)
    end
end

function CaptainTips:getColorCom()
    local n1 = cc.CSLoader:createNode(Res.CaptainTipsStr2Node)
    self:resetNodeSize(n1)
    local lastCnode = nil
    for i = 1, 15 do
        local cnode = n1:findChild("Panel/color_"..tostring(i))
        local snode = cnode:findChild("Panel/selected")
        snode:hide()
        local cimg = cnode:findChild("Panel/bg")
        local cid = 88511000 + i
        local cfgcolor = self.model:c3bFromCollectID(cid)
        cimg:setColor(cfgcolor)
        cnode:findChild("Panel"):addClickEventListener(function(sender)
            snode:show()

            if lastCnode and lastCnode ~= cnode then
                lastCnode:findChild("Panel/selected"):hide()
            end
            lastCnode = cnode

            self.currentColorID = cid

            self:preViewString()
        end)

        if cid == self.currentColorID then
            snode:show()
            lastCnode = cnode
        end
    end
    return n1
end

function CaptainTips:getBgCom()
    local n1 = cc.CSLoader:createNode(Res.CaptainTipsStr3Node)
    self:resetNodeSize(n1)
    n1:findChild("Panel/tlt"):setString(L("lua_code_text_331"))

    local ids = {88522001, 88523001, 88524001}
    for i = 1, 3 do
        local icn = n1:findChild("Panel/icon_"..tostring(i))
        local cfg = self.model:collectConifg(ids[i])
        icn:findChild("Panel/icon"):loadTexture(cfg.iconPath.."/"..cfg.icon..".png")

        local mask = icn:findChild("Panel/mask")
        local sel = icn:findChild("Panel/selected")

        icn:findChild("Panel"):addClickEventListener(function(sender)
            self.currentBgID = checknumber(cfg.ID)
            
            -- if not self.model:hasCollect(checknumber(cfg.ID)) then
            --     display.pushToast(L("ErrHasntCollector"))
            -- end

            if self.lastBgSel then
                self.lastBgSel:hide()
            end

            self.lastBgSel = sel
            sel:show()
            -- if self.lastBgSel ~= sel then
            -- else
            --     self.lastBgSel = nil
            --     self.currentBgID = 0
            -- end
            
            self:preViewString()
        end)

        if checknumber(cfg.ID) == self.currentBgID then
            sel:show()
            self.lastBgSel = sel
        end

        if self.model:hasCollect(checknumber(cfg.ID)) then
            mask:hide()
        else
            mask:show()
        end
    end

    return n1
end

function CaptainTips:getFrameCom()
    local n1 = cc.CSLoader:createNode(Res.CaptainTipsStr3Node)
    self:resetNodeSize(n1)
    n1:findChild("Panel/tlt"):setString(L("lua_code_text_307"))

    local ids = {88532001, 88533001, 88534001}
    for i = 1, 3 do
        local icn = n1:findChild("Panel/icon_"..tostring(i))
        local cfg = self.model:collectConifg(ids[i])
        icn:findChild("Panel/icon"):loadTexture(cfg.iconPath.."/"..cfg.icon..".png")

        local mask = icn:findChild("Panel/mask")
        local sel = icn:findChild("Panel/selected")

        icn:findChild("Panel"):addClickEventListener(function(sender)
            self.currentFrameID = checknumber(cfg.ID)

            -- if not self.model:hasCollect(checknumber(cfg.ID)) then
            --     display.pushToast(L("ErrHasntCollector"))
            -- end
            
            if self.lastFrameSel then
                self.lastFrameSel:hide()
            end

            self.lastFrameSel = sel
            sel:show()
            -- if self.lastFrameSel ~= sel then
            -- else
            --     self.lastFrameSel = nil
            --     self.currentFrameID = 0
            -- end
            
            self:preViewString()
        end)

        if checknumber(cfg.ID) == self.currentFrameID then
            sel:show()
            self.lastFrameSel = sel
        end

        if self.model:hasCollect(checknumber(cfg.ID)) then
            mask:hide()
        else
            mask:show()
        end
    end

    return n1
end

function CaptainTips:refreshStr(data)
    self.titleLbl:setString(L"captain_title_set_text")
    self.btnLbl:setString(L("lua_code_text_347"))
    self.lstView:removeAllChildren()

    self.currentColorID = self._data.curColor
    self.currentBgID = self._data.curBg
    self.currentFrameID = self._data.curFrame
    self.locationID = 531
    self.currentCollectID = self.currentBgID

    self.lstView:pushBackCustomItem(self:getStrCom())
    self.lstView:pushBackCustomItem(self:getColorCom())
    self.lstView:pushBackCustomItem(self:getBgCom())
    self.lstView:pushBackCustomItem(self:getFrameCom())

    self.textField:setText(data.curStr)
    self.lastcaptainstring = data.curStr
end



return CaptainTips
